import { useRef , useState} from "react";

import { _upload } from "../../api"



let Index : React.FC = () => {
    const [ src , setSrc ] = useState<string>("");
    const files = useRef<HTMLInputElement>(null);
    const upload = async () => {
        // console.log(files.current?.files)
        const myFiles = (files.current?.files as FileList)[0];
        if(myFiles){
            //  判断上传的是否是图片
            const memeType = ["image/png" , "image/jpg" , "image/jpeg" , "image/gif"];
            if(memeType.includes(myFiles.type)){
                //  判断文件大小
                if(myFiles.size / 1024 / 1024 <=5){
                    const formData = new FormData();
                    formData.append("file",myFiles);
                    const { data } = await _upload(formData);
                    alert(data.msg);
                    if(data.code){
                        setSrc(data.url);
                    }
                }else{
                    alert("文件大小不能超过5MB")
                }
            }else{
                alert("格式错误")
            }
        }else{
            alert("请选择一张图片")
        }
    };
    return (
        <div>
            <input type="file" ref={files}/>
            <button onClick={() => upload()}>立即上传</button>
            <img src={src} alt="" />
        </div>
    )
};


export default Index;